// service/distribution/distribution.js
import http from '../../utils/http'
import util from '../../utils/util'
import config from '../../utils/config'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    walletList: [
      {
        name: '累计佣金（元）',
        number: '0'
      },
      {
        name: '订单总数（明细）',
        number: '0'
      }
    ],
    withdrawCardList: [
      {
        name: '待入账（元）',
        number: '1245.66'
      },
      {
        name: '提现中（元）',
        number: '110'
      },
      {
        name: '已提现（元）',
        number: '110'
      }
    ],
    withdrawMoeny: '0.00',
    group: {
      count: 0,
      list: []
    },
    showSharePopup: false,
    qrcode: '',
    isDistribution: 1000, // 是否是分销商 是200 未申请0 审核中-1 审核拒绝-2
    form: {
      name: '',
      identityNumber: '',
      fileList: [],
      imageList: []
    }
  },
  getIsDistribution() {
    return new Promise((resolve) => {
      http.post('user/examine', '', false, false).then(res => {
        if (res.code === 1) {
          resolve(res.data.status)
        }
      })
    })
  },
  inputChange(e) {
    const name = e.currentTarget.dataset.name
    const value = e.detail.value
    this.setData({
      ['form.' + name]: value
    })
  },
  modalContent() {
    const { isDistribution } = this.data
    let title = ''
    if (isDistribution === -1) {
      title = "正在审核中，请耐心等待！"
    } else if (isDistribution === -2) {
      title = "您的提交被驳回，请重新填写后提交！"
    }
    wx.showModal({
      title: title,
      content: '',
      showCancel: false,
      complete: (res) => {
        if (res.confirm) {
          if (isDistribution === -1) {
            wx.navigateBack()
          } else if (isDistribution === -2) {
            this.setData({
              isDistribution: 0
            })
          }
        }
      }
    })
  },
  toast(title) {
    wx.showToast({
      title,
      icon: 'none'
    })
  },
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: config.domain + '/api/common/upload',
      filePath: file.url,
      name: 'file',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        const rest = JSON.parse(res.data)
        if (rest.code != 1) return this.toast(rest.msg)
        this.setData({
          ['form.fileList']: [file],
          ['form.imageList']: [rest.data.fullurl]
        })
      },
    });
  },
  deleteImage(event) {
    const index = event.detail.index
    const { fileList, imageList } = this.data.form
    fileList.splice(index, 1)
    imageList.splice(index, 1)
    this.setData({
      ['form.fileList']: fileList,
      ['form.imageList']: imageList
    })
  },
  submit() {
    const { name, identityNumber, imageList } = this.data.form
    console.log(this.data.form, 'form');
    if (!name) return this.toast('请填写姓名')
    if (!identityNumber) return this.toast('请填写身份证号')
    if (!imageList.length) return this.toast('请上传身份证人像面')
    http.post('user/apply', {
      name: name,
      user_sn: identityNumber,
      user_sn_image: imageList[0]
    }, true).then(res => {
      this.toast('提交成功')
      this.setData({
        isDistribution: -1
      })
      this.modalContent()
    })
  },
  skipWithdrawRecord() {
    util.skip('/service/withdrawRecord/withdrawRecord')
  },
  skipWithdraw() {
    util.skip(`/service/withdraw/withdraw?withdrawMoeny=${this.data.withdrawMoeny}`)
  },
  getDistribution() {
    http.post('user/my_share_init', '', true).then(res => {
      if (res.code === 1) {
        const rest = res.data
        this.setData({
          ['walletList[0].number']: rest.total,
          ['walletList[1].number']: rest.order_total,
          withdrawMoeny: rest.share_money
        })
      }
    })
  },
  getGroup() {
    http.post('user/my_group', '', true).then(res => {
      if (res.code === 1) {
        const rest = res.data
        this.setData({
          group: rest
        })
      }
    })
  },
  getShareInfo() {
    http.post('user/qrcode', '', true).then(res => {
      if (res.code === 1) {
        const rest = res.data
        this.setData({
          qrcode: rest
        })
      }
    })
  },
  clickShare() {
    this.setData({
      showSharePopup: true
    })
  },
  onClosePopup() {
    this.setData({
      showSharePopup: false
    })
  },
  savePhoto() {
    wx.getImageInfo({
      src: this.data.qrcode,
      success: result => {
        wx.saveImageToPhotosAlbum({
          filePath: result.path,
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '保存成功',
            })
          },
          fail: err => {
            console.log(err);
            wx.showToast({
              icon: 'none',
              title: '保存失败',
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const status = await this.getIsDistribution()
    this.setData({
      isDistribution: status
    })
    if (status === -1 || status === -2) this.modalContent()
    if (status === 200) {
      this.getGroup()
      this.getShareInfo()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.isDistribution === 200) {
      this.getDistribution()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: ' ',
      path: '/service/distribution/distribution',
      imageUrl: this.data.qrcode
    }
  },
})